package ua.amsoft.brelok.service;

import java.io.InputStream;
import java.util.LinkedList;
import java.util.Queue;

import ua.amsoft.brelok.task.FetchAndUpdateDIDRTask;
import ua.amsoft.brelok.task.FetchAndUpdateDODRTask;
import ua.amsoft.brelok.task.FetchAndUpdateDURTask;
import android.content.Context;
import android.os.AsyncTask;

/**
 * Runs the application's data update processes
 * 
 * @author Tair Mustafaiev
 */
public class UpdateTaskProcessor {
    
    private final Context context;
    
    /**
     * Constructor
     * 
     * @param cntx - {@link Context}
     */
    public UpdateTaskProcessor(final Context cntx) {
        this.context = cntx;
    }
    
    /**
     * Updates widget's database with fetched data
     */
    public void update() {
        final Queue<AsyncTask<String, Void, InputStream>> asyncTasks = initTasksQueue();
        synchronized (asyncTasks) {
            while (!asyncTasks.isEmpty()) {
                final AsyncTask<String, Void, InputStream> task = asyncTasks.poll();
                task.execute("");
            }
        }
    }
    
    /**
     * @return {@link Queue} with {@link AsyncTask} objects
     */
    private Queue<AsyncTask<String, Void, InputStream>> initTasksQueue() {
        final Queue<AsyncTask<String, Void, InputStream>> asyncTasks = new LinkedList<AsyncTask<String, Void, InputStream>>();
        final AsyncTask<String, Void, InputStream> fetchDepartamentUsageReports = new FetchAndUpdateDURTask(
                this.context);
        
        final AsyncTask<String, Void, InputStream> fetchDepartamentInputDocsReports = new FetchAndUpdateDIDRTask(
                this.context);
        
        final AsyncTask<String, Void, InputStream> fetchDepartamentOutputDocsReports = new FetchAndUpdateDODRTask(
                this.context);
        
        asyncTasks.add(fetchDepartamentInputDocsReports);
        asyncTasks.add(fetchDepartamentOutputDocsReports);
        asyncTasks.add(fetchDepartamentUsageReports);
        return asyncTasks;
    }
}
